package com.zxy.zxyrpc.bootstrap;

import com.zxy.zxyrpc.RpcApplication;
import com.zxy.zxyrpc.config.RegistryConfig;
import com.zxy.zxyrpc.config.RpcConfig;
import com.zxy.zxyrpc.exception.RpcException;
import com.zxy.zxyrpc.model.ErrorCode;
import com.zxy.zxyrpc.model.ServiceMetaInfo;
import com.zxy.zxyrpc.model.ServiceRegisterInfo;
import com.zxy.zxyrpc.registry.LocalRegistry;
import com.zxy.zxyrpc.registry.Registry;
import com.zxy.zxyrpc.registry.RegistryFactory;
import com.zxy.zxyrpc.server.VertxServerFactory;
import com.zxy.zxyrpc.server.tcp.VertxTcpServer;
import com.zxy.zxyrpc.utils.LogUtils;

import java.util.List;

/**
 * 服务提供者启动类
 *
 * @author zxy
 * @since 2025/5/29
 **/
public class ProviderBootStrap {
    /**
     * 服务初始化
     *
     * @param serviceRegisterInfoList 注册服务列表
     */
    public static void init(List<ServiceRegisterInfo<?>> serviceRegisterInfoList) {
        // RPC框架初始化（RPC 配置/注册中心）
        RpcApplication.getRpcConfig();
        RpcConfig rpcConfig = RpcApplication.getRpcConfig();
        RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
        Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());

        // 注册服务
        ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
        for (ServiceRegisterInfo<?> serviceRegisterInfo : serviceRegisterInfoList) {
            // 本地注册
            String serviceName = serviceRegisterInfo.getServiceName();
            LocalRegistry.register(serviceName, serviceRegisterInfo.getImplClass());

            serviceMetaInfo.setServiceName(serviceName);
            // 1、自定义不同版本号
            serviceMetaInfo.setServiceVersion(serviceRegisterInfo.getServiceVersion());
            ///2、统一版本号
            // serviceMetaInfo.setServiceVersion(rpcConfig.getVersion());
            serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
            serviceMetaInfo.setServicePort(rpcConfig.getServerPort());

            // 注册中心注册
            try {
                registry.registry(serviceMetaInfo);
            } catch (Exception e) {
                throw new RpcException(ErrorCode.PARAMS_ERROR, "服务注册异常");
            }
            LogUtils.OkLog(String.format("服务: {} 注册成功",serviceRegisterInfo));
        }
        // 服务提供者提供服务，同时开启心跳检测
        registry.heartBeat();
        // 启动服务器
        // VertxTcpServer vertxTcpServer = new VertxTcpServer();
        // vertxTcpServer.doStart(rpcConfig.getServerPort());
        VertxServerFactory.getInstance(rpcConfig.getVertxServer()).doStart(rpcConfig.getServerPort());
    }
}
